<template>
  <a-modal title="新建文章" :width="1000" :visible="visible" :confirmLoading="loading" @ok="handleSubmit()"
    @cancel="handleCancel">
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="form" :rules="rules" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-model-item label="文章名称" prop="title">
          <a-input v-model="form.title" placeholder="请输入文章名称" />
        </a-form-model-item>
        <a-form-model-item label="文章作者" prop="authorId">
          <a-select v-model="form.authorId" :placeholder="'请选择文章作者'" size="large">
            <a-select-option v-for="item in authorList" :key="item.id" :value="item.id">{{ item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="文章类型" prop="classId">
          <a-select v-model="form.classId" :placeholder="'请选择文章类型'" size="large">
            <a-select-option v-for="item in typeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="封面图">
          <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
            :customRequest="handleUpload" :before-upload="beforeUpload">
            <img v-if="form.image" :src="form.image" alt="avatar" />
            <div v-else>
              <a-icon :type="uploading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="内容" :labelCol="labelCol" :wrapperCol="{
          xs: { span: 17 },
          sm: { span: 17 }
        }">
          <Editor :value="form.content" @change="editorChange"></Editor>

        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import Editor from '@/components/Editor/QuillEditor.vue'
import commonApi from '@/api/common/common'
import api from '@/api/baike/article'
// 表单字段
const fields = ['description', 'pid']

export default {
  components: {
    Editor,
  },
  props: {
    // visible: {
    //   type: Boolean,
    //   required: true
    // },
    // loading: {
    //   type: Boolean,
    //   default: () => false
    // },
    model: {
      type: Object,
      default: () => null
    }
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 }
      },
      form: {
        id: undefined,
        title: null,
        authorId: undefined,
        classId: undefined,
        image: null,
        type: 'image',
        content: undefined,
      },
      rules: {
        title: [
          { required: true, message: '文章名称不能为空', trigger: 'blur' },
        ],
        authorId: [
          { required: true, message: '请选择文章作者', trigger: 'blur' },
        ],
        classId: [
          { required: true, message: '请选择文章分类', trigger: 'blur' },
        ]

      },
      imageUrl: null,
      uploading: false,
      loading: false,
      authorList: [],
      typeList: [],
      visible: false,
    }
  },
  created() {
    this.getAuthor()
    this.getType()
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate(valid => {        
        if (valid) {
          if (this.form.id) {
            api.update(this.form).then(res => {
              this.loading = false
              this.$message.success('修改成功');
              this.visible = false
              this.$emit('ok')
            })
          } else {
            api.add(this.form).then(res => {
              this.loading = false
              this.$message.success('添加成功');
              this.visible = false
              this.$emit('ok')
            })
          }

        }
      })
    },
    editorChange(e) {
      this.form.content = e
      
    },
    //  获取作者列表
    getAuthor() {
      api.getAuthorList().then(res => {
        this.authorList = res.data.dataList
      })
    },
    //  获取类型列表
    getType() {
      api.getTypeList().then(res => {
        this.typeList = res.data.dataList
      })
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    async handleUpload(options) {
      const { onProgress, onError, onSuccess, file } = options;

      try {
        this.uploading = true;

        // 使用你的API上传文件
        const formData = new FormData();
        formData.append('file', file);

        const response = await commonApi.uploadFile(formData);

        // 上传成功处理
        this.form.image = response.data.fileHttp; // 假设返回数据中有url字段
        onSuccess(response, file);
        this.$message.success('上传成功');
      } catch (error) {
        onError(error);
        this.$message.error('上传失败');
      } finally {
        this.uploading = false;
      }
    },
    show(val = null) {
      this.visible = true

      if (val) {
        this.form = {
          id: val.id,
          title: val.title,
          authorId: val.authorId,
          classId: val.classId,
          image: val.image,
          type: val.type,
          content: val.content,
        }
      } else {
        this.form = {
          id: undefined,
          title: null,
          authorId: undefined,
          classId: undefined,
          image: null,
          type: 'image',
          content: undefined,
        }
      }
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>
